/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.scriptmark.core.dispose;

import com.jspx.scriptmark.Phrase;
import com.jspx.scriptmark.ScriptRunner;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.core.EnvRunner;
import com.jspx.scriptmark.core.block.AssignBlock;
import com.jspx.utils.StringUtil;
import org.mozilla.javascript.NativeObject;
import java.io.Writer;
import java.io.StringWriter;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2009-1-2
 * Time: 16:08:35
 * Phrase
 */
public class AssignPhrase implements Phrase {
    public int getRun(EnvRunner env, TagNode tagNode, Writer out) throws Exception {

        AssignBlock assignBlock = (AssignBlock) tagNode;
        String type = assignBlock.getType();
        String in = assignBlock.getIn();
        List<TagNode> list = assignBlock.getValueList();
        Writer aw = new StringWriter();
        for (TagNode node : list) {
            if (AssignBlock.script.equalsIgnoreCase(type)) {
                env.runBlock(node, aw);
            } else aw.write(node.getSource());
        }

        ScriptRunner scriptEngine = env.getScriptRunner();
        if (StringUtil.hasLength(in)) {
            /**
             * 为了支持这种写法
             * <#assign mail="chen@other.com" in=my>
             * <#assign mail="jsmith@other.com" in=you>
             * ${my.mail}, ${you.mail}
             */
            NativeObject jsObject = new NativeObject();
            jsObject.setParentScope(scriptEngine.getScope());
            jsObject.put(assignBlock.getVarName(), jsObject, scriptEngine.eval(aw.toString(),assignBlock.getLineNumber()));
            scriptEngine.put(in, jsObject);
        } else {
            if (AssignBlock.script.equalsIgnoreCase(type)) {
                scriptEngine.putVar(assignBlock.getVarName(), aw.toString());
            } else {
                scriptEngine.put(assignBlock.getVarName(), aw.toString());
            }
        }
        list.clear();
        return 0;
    }
}